package it.uniroma2.imagetranscoder;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.Imaging;

import com.yammer.metrics.Meter;
import com.yammer.metrics.Timer;

@SuppressWarnings("serial")
public class TranscoderServlet extends HttpServlet {

	private Meter serviceRate = WebAppContextListener.mRegistry
			.meter("serviceRate");
	private Timer processingDuration = WebAppContextListener.mRegistry
			.timer("processing-duration");

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		InputStream filecontent = null;
		final Timer.Context context = processingDuration.time();
		try {
			@SuppressWarnings("unchecked")
			List<FileItem> items = new ServletFileUpload(
					new DiskFileItemFactory()).parseRequest(request);
			//ImageTranscoder imageTranscoder = new ImageTranscoder();
			NioTransferCopy nioTransferCopy = new NioTransferCopy(getClass().getClassLoader().getResource("").getFile());
			int filterToApply = -1;
			for (FileItem item : items) {
				if (item.isFormField()) {
					// Process regular form field (input
					// type="text|radio|checkbox|etc", select, etc).
					if (item.getFieldName().equals("filter")) {
						filterToApply = Integer.parseInt(item.getString());
					}
				} else {
					// Process form file field (input type="file").
					// Process form file field (input type="file").
					// String fieldname = item.getFieldName();
					// String filename = FilenameUtils.getName(item.getName());
					filecontent = item.getInputStream();

//					ImageResponse imageResponse = imageTranscoder.apply(
//							filterToApply, filecontent);
					
					//NIO
					// Process form file field (input type="file").
					//filecontent = item.getInputStream();

				    File fileOut = new File(getClass().getClassLoader().getResource("").getFile()+File.separator+"fileOut_"+UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+".tmp");
				   
				    File fileIn = nioTransferCopy.inputstreamToFile(filecontent);
					nioTransferCopy.nioTransferCopy(fileIn, fileOut);

					//ResizeImage
					BufferedImage originalImage;
					try {
						//long start = System.currentTimeMillis();
						originalImage = Imaging.getBufferedImage(fileOut);
						BufferedImage resizedImage = new BufferedImage(200, 200, originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType());
						Graphics2D g = resizedImage.createGraphics();
						g.drawImage(originalImage, 0, 0, 200, 200, null);
						g.dispose();
						//long end = System.currentTimeMillis();
						//System.out.println("Duration: " + (end-start) );
					} catch (ImageReadException e) {
						e.printStackTrace();
					}

					
					
					fileIn.delete();
					fileOut.delete();

					response.setStatus(200);
					response.setContentType("text/html");
					response.getWriter().println("YesYouCan");
					//if you want to return the image
					// response.setContentType(imageResponse.getContentType());
					// OutputStream out = response.getOutputStream();
					// ImageIO.write(imageResponse.getBufferedImage(),
					// imageResponse.getExt(), out);
					// out.close();

				}
			}
			serviceRate.mark();
		} catch (FileUploadException e) {
			throw new ServletException("Cannot parse multipart request.", e);
		} finally {
			context.stop();
			if (filecontent != null) {
				filecontent.close();
			}
		}
	}
}
